package com.example.neteaseapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.neteaseapplication.entity.LrcRow;
import com.example.neteaseapplication.entity.Song;
import com.example.neteaseapplication.inter.ILrcBuilder;
import com.example.neteaseapplication.inter.ILrcView;
import com.example.neteaseapplication.inter.ILrcViewListener;
import com.example.neteaseapplication.service.MusicService;
import com.example.neteaseapplication.util.ATagToJson;
import com.example.neteaseapplication.util.BlurUtil;
import com.example.neteaseapplication.util.DefaultLrcBuilder;
import com.example.neteaseapplication.util.DisplayUtil;
import com.example.neteaseapplication.util.GetHtmlUtil;
import com.example.neteaseapplication.util.LocalMusicUtils;
import com.example.neteaseapplication.widget.BackgroundRelativeLayout;
import com.example.neteaseapplication.widget.DiscView;
import com.example.neteaseapplication.widget.LrcView;

import org.json.JSONArray;
import org.json.JSONObject;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class MusicPlayingActivity extends Activity implements DiscView.IPlayInfo, View.OnClickListener {

    private DiscView mDisc;
    private SeekBar mSeekBar;
    private ImageView mIvPlayOrPause;
    private ImageView mIvNext;
    private ImageView mIvLast;
    private TextView mTvMusicDuration, mTvTotalMusicDuration;
    private BackgroundRelativeLayout mRootLayout;
    public static final int MUSIC_MESSAGE = 0;
    private Song mSong;
    private MusicService.MusicBinder mMusicBinder;
    private int currentIndex;
    private TextView mtvPlayingName;
    private TextView mTvPlayingSinger;
    private MediaPlayer mMediaPlayer;
    private LinearLayout mPlaingLayout;
    private LinearLayout mLrcLayout;
    private View mView;
    private int flag = 0;

    /**
     * 自定义LrcView，用来展示歌词
     */
    private ILrcView mLrcView;
    /**
     * 更新歌词的频率，每100ms更新一次
     */
    private int mPlayerTimerDuration = 100;
    /**
     * 更新歌词的定时器
     */
    private Timer mTimer;
    /**
     * 更新歌词的定时任务
     */
    private TimerTask mTask;
    private ILrcBuilder mBuilder;


    public static final String PARAM_MUSIC_LIST = "PARAM_MUSIC_LIST";

    @SuppressLint("HandlerLeak")
    private Handler mMusicHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mMusicBinder.getMediaPlayer() != null) {
//                mMediaPlayer = new MediaPlayer();
                mMediaPlayer = mMusicBinder.getMediaPlayer();
                mSeekBar.setProgress(mMediaPlayer.getCurrentPosition() + 1000);
                mTvMusicDuration.setText(duration2Time(mSeekBar.getProgress()));
            }
            startUpdateSeekBarProgress();
        }
    };

    private List<Song> mSongList = new ArrayList<>();
//    private Callback mCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_playing);

//        initMusic();
        initView();
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
//        makeStatusBarTransparent();
        Intent intent = getIntent();
        mMusicBinder = (MusicService.MusicBinder) intent.getSerializableExtra("binder");
        mSongList = intent.getParcelableArrayListExtra("songs");
        mSong = intent.getParcelableExtra("song");
        currentIndex = intent.getExtras().getInt("id");
//        intent.getInt
        if (currentIndex != -1) {
//            int index  = Integer.parseInt(intent.getStringExtra("index"));
            mDisc.setSongList(currentIndex, mSongList);
            initMusicMsg();
            changeButtonAttr();
            new Thread(lrcTask).start();
        }
        updateMusicDurationInfo(mSong.getDuration());
        if (mMediaPlayer != null) {

            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (currentIndex <= mSongList.size() - 1) {
                        next();
                    }
                }
            });
        }

//        requestLrcData(mSong.getName(),mCallback);
    }

    Runnable lrcTask = new Runnable() {
        @Override
        public void run() {
            showLrc();
        }
    };

    private void showLrc() {
        /*String nameId = ATagToJson.convertHtml("https://music.163.com/#/search/m/?s=" + LrcContent(mSong)+"&type=1", LrcContent(mSong));
        int id = Integer.parseInt(nameId.substring(9));*/
        try {
            GetHtmlUtil.lianjie();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String lrc = getLrcFromAssets("http://music.163.com/api/song/media?id=" + 1374051000);
        //解析歌词构造器
        mBuilder = new DefaultLrcBuilder();
        //解析歌词返回LrcRow集合

        List<LrcRow> rows = mBuilder.getLrcRows(lrc);
        //将得到的歌词集合传给mLrcView用来展示
        mLrcView.setLrc(rows);
        mLrcView.setLoadingTipText(rows.toString());
        //开始播放歌曲并同步展示歌词
        beginLrcPlay();
        //设置自定义的LrcView上下拖动歌词时监听
        mLrcView.setListener(new ILrcViewListener() {
            //当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
            public void onLrcSought(int newPosition, LrcRow row) {
                if (mMediaPlayer != null) {

                    Log.d(TAG, "onLrcSought:" + row.startTime);
                    mMediaPlayer.seekTo((int) row.startTime);
                }
            }
        });
    }


    private void beginLrcPlay() {
        if (mMediaPlayer != null) {
            if (mTimer == null) {
                mTimer = new Timer();
                mTask = new LrcTask();
                mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
            }
        }
    }

    /**
     * 展示歌曲的定时任务
     */
    class LrcTask extends TimerTask {
        @Override
        public void run() {
            //获取歌曲播放的位置
            if(mMediaPlayer.getCurrentPosition() >= 0){

                final long timePassed = mMediaPlayer.getCurrentPosition();
                MusicPlayingActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //滚动歌词

                        mLrcView.seekLrcToTime(timePassed);
                    }
                });
            }

        }
    }

    /**
     * 初始化音乐
     */
    /*public void initMusic() {
        mSongList = LocalMusicUtils.getmusic(this);

    }*/
    public void changeButtonAttr() {
        if (mMediaPlayer != null) {

            if (mMediaPlayer.isPlaying()) {

                mIvPlayOrPause.setBackgroundResource(R.drawable.ic_pause);
                mDisc.playOrPause();
            } else {
                mIvPlayOrPause.setBackgroundResource(R.drawable.ic_play);
            }
        } else {
            mIvPlayOrPause.setBackgroundResource(R.drawable.ic_play);
        }
    }

    /**
     * 标题栏歌曲信息
     */
    public void initMusicMsg() {
        String name = mSong.getName();
        mtvPlayingName.setText(name.substring(0, name.length() - 4));
        mTvPlayingSinger.setText(mSong.getSinger());
    }

    /**
     * 获取歌名
     *
     * @param song
     * @return
     */
    public String LrcContent(Song song) {
        return song.getName().substring(0, song.getName().length() - 4).trim();
    }

    private void initView() {
        mDisc = findViewById(R.id.discview);
        mIvNext = findViewById(R.id.ivNext);
        mIvLast = findViewById(R.id.ivLast);
        mIvPlayOrPause = findViewById(R.id.ivPlayOrPause);
        mTvMusicDuration = findViewById(R.id.tvCurrentTime);
        mTvTotalMusicDuration = findViewById(R.id.tvTotalTime);
        mSeekBar = findViewById(R.id.musicSeekBar);
        mRootLayout = findViewById(R.id.rootLayout);
        mtvPlayingName = findViewById(R.id.tv_playing_name);
        mTvPlayingSinger = findViewById(R.id.tv_playing_singer);
        mLrcView = findViewById(R.id.lv_lrc);
        mPlaingLayout = findViewById(R.id.layout_disc);
        mLrcLayout = findViewById(R.id.layout_lrc);
        mView = findViewById(R.id.vLrc);


        mDisc.setPlayInfoListener(this);
        mIvLast.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        mIvPlayOrPause.setOnClickListener(this);
        mDisc.setOnClickListener(this);
        mLrcLayout.setOnClickListener(this);
//        mPlaingLayout.setOnClickListener(this);
        mView.setOnClickListener(this);

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTvMusicDuration.setText(duration2Time(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopUpdateSeekBarProgree();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekTo(seekBar.getProgress());
                startUpdateSeekBarProgress();
            }
        });

        mTvMusicDuration.setText(duration2Time(0));
        mTvTotalMusicDuration.setText(duration2Time(0));
    }

    private void stopUpdateSeekBarProgree() {
        mMusicHandler.removeMessages(MUSIC_MESSAGE);
    }
    /*设置透明状态栏*//*
    private void makeStatusBarTransparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }*/

    public void seekTo(int process) {
        mMusicBinder.getMediaPlayer().seekTo(process);
    }

    private void try2UpdateMusicPicBackground(final Bitmap album) {
        if (mRootLayout.isNeed2UpdateBackground(album)) {
            new Thread(new Runnable() {
                final Drawable foregroundDrawable = getForegroundDrawable(album);

                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRootLayout.setForeground(foregroundDrawable);
                            mRootLayout.beginAnimation();
                        }
                    });
                }
            }).start();
        }
    }

    private Drawable getForegroundDrawable(Bitmap album) {
        /*得到屏幕的宽高比，以便按比例切割图片一部分*/
        final float widthHeightSize = (float) (DisplayUtil.getScreenWidth(MusicPlayingActivity.this));

        int cropBitmapWidth = (int) (widthHeightSize * album.getHeight()) / 1000;
        int cropBitmapWidthX = (int) ((album.getWidth() - cropBitmapWidth) / 2.0);

//        切割部分图片
        Bitmap cropBitmap = Bitmap.createBitmap(album, 0, 0, 20,
                album.getHeight());

//        缩小图片
        Bitmap scaleBitmap = Bitmap.createScaledBitmap(album, album.getWidth() / 10, album
                .getHeight() / 10, false);
        /*模糊化*/
//        final Bitmap blurBitmap = BlurUtil.doBlur(scaleBitmap, 10, true);
        final Bitmap blurBitmap = BlurUtil.doBlur(scaleBitmap, 1, 10);

        final Drawable foregroundDrawable = new BitmapDrawable(blurBitmap);
        /*加入灰色遮罩层，避免图片过亮影响其他控件*/
        foregroundDrawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
        return foregroundDrawable;
    }

   /* private Bitmap getForegroundBitmap(int musicPicRes) {
        int screenWidth = DisplayUtil.getScreenWidth(this);
        int screenHeight = DisplayUtil.getScreenHeight(this);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeResource(getResources(), musicPicRes, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        if (imageWidth < screenWidth && imageHeight < screenHeight) {
            return BitmapFactory.decodeResource(getResources(), musicPicRes);
        }

        int sample = 2;
        int sampleX = imageWidth / DisplayUtil.getScreenWidth(this);
        int sampleY = imageHeight / DisplayUtil.getScreenHeight(this);

        if (sampleX > sampleY && sampleY > 1) {
            sample = sampleX;
        } else if (sampleY > sampleX && sampleX > 1) {
            sample = sampleY;
        }

        options.inJustDecodeBounds = false;
        options.inSampleSize = sample;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeResource(getResources(), musicPicRes, options);
    }*/

    @Override
    public void onMusicPicChanged(Bitmap albumImg) {
        try2UpdateMusicPicBackground(albumImg);
    }

    @Override
    public void onMusicInfoChanged(String musicName, String musicAuthor) {

    }

    @Override
    public void onMusicChanged(DiscView.MusicChangedStatus musicChangedStatus) {
        switch (musicChangedStatus) {
            case PLAY: {
//                play();
                beginLrcPlay();
                mMusicBinder.start(mSong, MusicPlayingActivity.this);
                changeButtonAttr();
                break;
            }
            case PAUSE: {
//                pause();
                mMusicBinder.pause();
                changeButtonAttr();
                break;
            }
            case NEXT: {
                next();
                break;
            }
            case LAST: {
                last();
                break;
            }
            case STOP: {
//                stop();
                break;
            }
        }
    }

    /**
     * 上一首
     */
    private void last() {
        currentIndex--;
        if (currentIndex == 0) {
//            mSong = mSongList.get()
//            mSong = mSongList.get(mSongList.size()-1);
//            mIvPlayOrPause.setBackgroundResource(R.drawable.ic_play);
        } else {
            mSong = mSongList.get(currentIndex - 1);
            mIvPlayOrPause.setBackgroundResource(R.drawable.ic_pause);
            initMusicMsg();
        }
        mMusicBinder.start(mSong, MusicPlayingActivity.this);
        updateMusicDurationInfo(mSong.getDuration());
    }

    /**
     * 下一首
     */
    private void next() {
        currentIndex++;
        if (currentIndex < mSongList.size() - 1) {
            mSong = mSongList.get(currentIndex);
            mIvPlayOrPause.setBackgroundResource(R.drawable.ic_pause);
            initMusicMsg();
        } else {
//            mSong = mSongList.get(0);
        }
        mMusicBinder.start(mSong, MusicPlayingActivity.this);
        updateMusicDurationInfo(mSong.getDuration());
    }

    @Override
    public void onClick(View v) {
        if (v == mIvPlayOrPause) {
            mDisc.playOrPause();
        } else if (v == mIvNext) {
            mDisc.next();
        } else if (v == mIvLast) {
            mDisc.last();
        }
        switch (v.getId()) {
            case R.id.discview:
                mDisc.setVisibility(View.GONE);
                mLrcLayout.setVisibility(View.VISIBLE);
                flag = 1;
                break;
            case R.id.layout_lrc:
                mDisc.setVisibility(View.VISIBLE);
                mLrcLayout.setVisibility(View.GONE);
                break;
            default:
                break;
        }

    }

    public void ChangePage(View view) {

    }

   /* private void stop() {
        stopUpdateSeekBarProgree();
        mIvPlayOrPause.setBackgroundResource(R.drawable.ic_play);
        mTvMusicDuration.setText(duration2Time(0));
        mTvTotalMusicDuration.setText(duration2Time(0));
        mSeekBar.setProgress(0);
    }*/

/*    private void complete(boolean isOver) {
        if (isOver) {
            mDisc.stop();
        } else {
            mDisc.next();
        }
    }

    private void optMusic(final String action) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(action));
    }*/


    private void startUpdateSeekBarProgress() {
        /*避免重复发送Message*/
        stopUpdateSeekBarProgree();
        mMusicHandler.sendEmptyMessageDelayed(0, 1000);
    }

    /*根据时长格式化称时间文本*/
    private String duration2Time(int duration) {
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;

        return (min < 10 ? "0" + min : min + "") + ":" + (sec < 10 ? "0" + sec : sec + "");
    }

    private void updateMusicDurationInfo(int totalDuration) {
        mSeekBar.setProgress(0);
        mSeekBar.setMax(totalDuration);
        mTvTotalMusicDuration.setText(duration2Time(totalDuration));
        mTvMusicDuration.setText(duration2Time(0));
        startUpdateSeekBarProgress();
    }


    /*private void requestLrcData(final String name, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String MusicName = name.trim();//去掉空格
        String NameId = ATagToJson.convertHtml("https://music.163.com/#/search/m/?s=" + MusicName, MusicName);
        Request request = new Request.Builder().url("http://music.163.com/api/song/media?id=" + Integer.parseInt(NameId)).build();
        okHttpClient.newCall(request).enqueue(callback);

    }*/


   /* public static String parseJOSNWithGSON(Response response, int c) {
        try {
            String ResponseData = response.body().string();
            JSONObject jsonObject = new JSONObject(ResponseData);
            int count = Integer.parseInt(jsonObject.getString("count"));
            Log.i("TAG", "parseJOSNWithGSONCOUNT:" + count);
            if (count >= c) {
                String result = jsonObject.getString("result");
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject1 = jsonArray.getJSONObject(c - 1);
                String url = jsonObject1.getString("lrc");
                Log.i("TAG", "parseJOSNWithGSON:1 " + url);
                return url;
            } else {
                Log.i("TAG", "parseJOSNWithGSON: " + c);
                return "";
            }
        } catch (Exception e) {

        }
        return "";

    }*/

    public static String getLrcFromAssets(String Url) {
        Log.i("first", "getLrcFromAssets: " + Url);
        StringBuilder result = new StringBuilder();
        if (Url.equals("")) {
            return "";
        }
        try {
            URL url = new URL(Url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            /*String lrcPath = Environment.getExternalStorageState()+"/storage/emulated/0/Download/薛之谦 - 木偶人.lrc";
            InputStream input = new FileInputStream(new File(lrcPath));*/
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            InputStream input = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));

            String line = "";
            while ((line = in.readLine()) != null) {
                //逐行读取
                if (line.trim().equals("")) continue;
//                String[] lrc = line.split("\n");
                JSONObject jsonObject = new JSONObject(line);
                String lrc = jsonObject.getString("lyric");
                String lineResult = lrc.replace("\\n", "\r\n");
                result.append(lineResult);
                Log.i("first", "getLrcFromAssets: " + result);
            }
            Log.i("total", "getLrcFromAssets: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }
    /*public static String getAllHtml(String url) {
        StringBuilder input = new StringBuilder();
        try {

            InputStreamReader in = new InputStreamReader(new URL(url).openStream());
            int ch;
            while ((ch = in.read()) != -1) {
                input.append((char) ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input.toString();
    }*/
}




